from datetime import datetime
from PIL import Image, ImageDraw, ImageEnhance
import StringIO
import urllib
import os
import time
import threading

def download_image(url):
   """
   Download picture from URL
   """
   try:
      f = urllib.urlopen(url)
      sio = StringIO.StringIO(f.read())
      return Image.open(sio)
   except IOError:
      return None

def reduce_opacity(im, opacity):
    """Returns an image with reduced opacity."""
    assert opacity >= 0 and opacity <= 1
    if im.mode != 'RGBA':
        im = im.convert('RGBA')
    else:
        im = im.copy()
    alpha = im.split()[3]
    alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
    im.putalpha(alpha)
    return im

def imprint(im, inputtext, font=None, color=None, opacity=.6, margin=(30,30)):
   """
   Imprints a PIL image with the indicated text in lower-right corner
   """
   if im.mode != "RGBA":
      im = im.convert("RGBA")
   textlayer = Image.new("RGBA", im.size, (0,0,0,0))
   textdraw = ImageDraw.Draw(textlayer)
   textsize = textdraw.textsize(inputtext, font=font)
   textpos = [im.size[i]-textsize[i]-margin[i] for i in [0,1]]
   textdraw.text(textpos, inputtext, font=font, fill=color)
   if opacity != 1:
      textlayer = reduce_opacity(textlayer,opacity)
   return Image.composite(textlayer, im, textlayer)

class CaptureThread(threading.Thread):
   """Thread that captures one frame"""

   def run(self):
      now = datetime.now()
      timestamp = now.strftime("%a %d/%m/%Y %H:%M")
      image = download_image("http://www.dorbreizh.fr/Upload/envoi_image.jpg")
      if image:
         print("Snapshot " + now.strftime(timestamp))
         image.thumbnail((640, 443), Image.ANTIALIAS)
      else:
         print("Missed " + now.strftime(timestamp))
         image = Image.new("RGBA", (640,443), "white")
      image = imprint(image, timestamp, color="black")
      dir = now.strftime("%Y_%m_%d_%a")
      if not os.path.exists(dir):
         os.mkdir(dir)
      filename = os.path.join(dir, now.strftime("%Y%m%d_%H%M") + ".jpg")
      image.save(filename, quality=50)

if __name__ == "__main__":
   try:
      while 1:
         CaptureThread().start()
         time.sleep(60.0)
   except KeyboardInterrupt:
      t.shutdown()
